package cn.com.headfree.technician.service.impl;

import cn.com.headfree.base.controller.ResultData;
import cn.com.headfree.callback.call.FileServerCall;
import cn.com.headfree.entity.TEmpBaseInfo;
import cn.com.headfree.entity.TSeniorTechnician;
import cn.com.headfree.entity.TouXiangVo;
import cn.com.headfree.technician.service.WordExportService;
import cn.com.headfree.util.DetailTablePolicy;
import cn.com.headfree.vo.*;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.data.*;
import com.deepoove.poi.data.style.Style;
import com.deepoove.poi.data.style.TableStyle;
import com.gta.edu.sdk.util.StringUtil;
import feign.Response;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STJc;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 导出word工具类
 */
@Service("wordExportService")
public class WordExportServiceImpl implements WordExportService {

    private static final Logger log = LogManager.getLogger(WordExportServiceImpl.class);

    @Autowired
    private FileServerCall fileServerCall;

    /**
     * 在本地生成word文档
     * @param response
     * @param data              结果对象
     * @param filename            本地生成word名称
     */
    @Override
    public void exportWord(HttpServletResponse response, TechnicalReportVo data, String filename ,String erpNo){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年M月d日");
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy年M月");
        FileOutputStream out=null;
        XWPFTemplate template = null;
        InputStream inputStream = null;
        File file = null;
        PaymentData datas = new PaymentData();//数据封装
        //样式
        Style textStyle = new Style();
        TableStyle headStyle = new TableStyle();
        TableStyle rowStyle = new TableStyle();
        rowStyle.setAlign(STJc.Enum.forInt(2));
        textStyle.setFontFamily("仿宋_GB2312");
        textStyle.setFontSize(12);
        textStyle.setColor("000000");
        headStyle.setAlign(STJc.CENTER);

        TEmpBaseInfo baseInfo = data.gettEmpBaseInfo();
        if(baseInfo != null){
            datas.setName(baseInfo.getName());
            datas.setUnit(baseInfo.getUnit());
            datas.setIdCardNo(baseInfo.getIdCardNo());
            datas.setMobilePhone(baseInfo.getMobilePhone());
            datas.setSex(baseInfo.getSex());
            datas.setNation(baseInfo.getNation());
            datas.setCurPost(baseInfo.getCurPost());
        }

        TSeniorTechnician technician = data.gettSeniorTechnician();
        if(technician != null){
            datas.setEduInfo(technician.getEduInfo());
            datas.setCurrentSubjLevel(technician.getCurrentSubjLevel());
            datas.setReadySubjLevel(technician.getReadySubjLevel());
            if(technician.getAcquTime() != null){
                datas.setAcquTime(sdf.format(technician.getAcquTime()));
                int currentYear = Calendar.getInstance().get(Calendar.YEAR);//当前年度
                int year = new Integer(String.format("%tY", technician.getAcquTime()));//获取现资格的年度
                int yearCount = currentYear - year;
                int currentMonth = Calendar.getInstance().get(Calendar.MONTH)+1;//当前月份
                int month = new Integer(String.format("%tm", technician.getAcquTime()));//获取现资格的年度
                if(currentMonth > month){
                    yearCount++;
                }
                if(yearCount > 0){
                    datas.setCurrentMajorYear(yearCount+"年");
                }
            }
        }

        //工作经历--组合列头
        RowRenderData header1 = RowRenderData.build(
                new TextRenderData("起止年月",textStyle),
                new TextRenderData("工作单位",textStyle),
                new TextRenderData("工作岗位（职务）",textStyle),
                new TextRenderData("证明人",textStyle));
        header1.setRowStyle(headStyle);
        //工作经历--组合数据内容
        List<WorkExpInfoVo> workExpInfoVos = data.getWorkExpInfoVos();
        List<RowRenderData> workRowList = new ArrayList<>();
        if(workExpInfoVos != null && workExpInfoVos.size() > 0){
            for(WorkExpInfoVo vo:workExpInfoVos){
//            for(int i=workExpInfoVos.size()-1;i>=0;i--){
                if(vo.getIsHide() == null || !(vo.getIsHide().equals("0"))){
                    String start = "";
                    String end = "";
                    if(vo.getStartTime() != null){
                        start = sdf.format(vo.getStartTime());
                    }
                    if(vo.getEndTime() != null){
                        end = sdf.format(vo.getEndTime());
                    }
                    RowRenderData row = RowRenderData.build(new TextRenderData(start+"-"+end, textStyle),
                            new TextRenderData(vo.getCompany(), textStyle), new TextRenderData(vo.getPost(), textStyle),
                            new TextRenderData(vo.getCertifier(), textStyle));
                    row.setRowStyle(rowStyle);
                    workRowList.add(row);
                }
            }
        }
        RowRenderData row1 = RowRenderData.build("","","","");//加一行空行
        workRowList.add(row1);
        MiniTableRenderData miniTableRenderData1 = new MiniTableRenderData(header1, workRowList,MiniTableRenderData.WIDTH_A4_FULL);
        miniTableRenderData1.setStyle(headStyle);
        datas.setWorkExpInfoVo(miniTableRenderData1);

        //主要学习、培训经历组合列头
        RowRenderData header2 = RowRenderData.build(
                new TextRenderData("起止年月",textStyle),
                new TextRenderData("学校或培训单位",textStyle),
                new TextRenderData("学习培训内容",textStyle),
                new TextRenderData("证明人",textStyle));
        header2.setRowStyle(headStyle);
        //主要学习、培训经历组合数据内容
        List<StudyAndTrainVo> studyAndTrainVos = data.getStudyAndTrainVo();
        List<RowRenderData> studyRowList = new ArrayList<>();
        if(studyAndTrainVos != null && studyAndTrainVos.size() > 0){
            for(StudyAndTrainVo vo:studyAndTrainVos){
//            for(int i=studyAndTrainVos.size()-1;i>=0;i--){
                if(vo.getIsHide() == null || !(vo.getIsHide().equals("0"))) {
                    String start = "";
                    String end = "";
                    if (vo.getStartTime() != null) {
                        start = sdf.format(vo.getStartTime());
                    }
                    if (vo.getEndTime() != null) {
                        end = sdf.format(vo.getEndTime());
                    }
                    RowRenderData row = RowRenderData.build(new TextRenderData(start + "-" + end, textStyle),
                            new TextRenderData(vo.getSchoolAndUnit(), textStyle), new TextRenderData(vo.getMajor(), textStyle),
                            new TextRenderData(vo.getCertifier(), textStyle));
                    row.setRowStyle(rowStyle);
                    studyRowList.add(row);
                }
            }
        }
        RowRenderData row2 = RowRenderData.build("","","","");//加一行空行
        studyRowList.add(row2);
        MiniTableRenderData miniTableRenderData2 = new MiniTableRenderData(header2, studyRowList,MiniTableRenderData.WIDTH_A4_FULL);
        miniTableRenderData2.setStyle(headStyle);
        datas.setStudyAndTrainVo(miniTableRenderData2);

        DetailTable detailTable = new DetailTable();
        //技术革新、专利、科技创新、项目成果
        List<SkillAndTechnicalVo> skillAndTechnicalVos = data.getSkillAndTechnicalVo();
        List<RowRenderData> skillRowList = new ArrayList<>();
        RowRenderData row3 = RowRenderData.build("","","","");//加一行空行
        skillRowList.add(row3);
        if(skillAndTechnicalVos != null && skillAndTechnicalVos.size() > 0){
//            for(SkillAndTechnicalVo vo:skillAndTechnicalVos){
            for(int i=skillAndTechnicalVos.size()-1;i>=0;i--){
                if(skillAndTechnicalVos.get(i).getIsHide() == null || !(skillAndTechnicalVos.get(i).getIsHide().equals("0"))) {
                    String start = "";
                    String end = "";
                    if (skillAndTechnicalVos.get(i).getStartTime() != null) {
                        start = sdf.format(skillAndTechnicalVos.get(i).getStartTime());
                    }
                    if (skillAndTechnicalVos.get(i).getEndTime() != null) {
                        end = sdf.format(skillAndTechnicalVos.get(i).getEndTime());
                    }
                    if (!StringUtil.isNullOrEmpty(end)) {
                        start = start + "-";
                    }
                    RowRenderData row = RowRenderData.build(new TextRenderData(start + end, textStyle),
                            new TextRenderData(skillAndTechnicalVos.get(i).getProjectName(), textStyle), new TextRenderData(skillAndTechnicalVos.get(i).getMyDuty(), textStyle),
                            new TextRenderData(skillAndTechnicalVos.get(i).getEncourage(), textStyle));
                    row.setRowStyle(rowStyle);
                    skillRowList.add(row);
                }
            }
        }
        detailTable.setSkillAndTechnicalVo(skillRowList);

        //标准制定、学术成果
        List<StandAndScienceVo> standAndScienceVo = data.getStandAndScienceVo();
        List<RowRenderData> standRowList = new ArrayList<>();
        RowRenderData row4 = RowRenderData.build("","","","");//加一行空行
        standRowList.add(row4);
        if(standAndScienceVo != null && standAndScienceVo.size() > 0){
//            for(StandAndScienceVo vo:standAndScienceVo){
            for(int i=standAndScienceVo.size()-1;i>=0;i--){
                if(standAndScienceVo.get(i).getIsHide() == null || !(standAndScienceVo.get(i).getIsHide().equals("0"))) {
                    String pubTime = "";
                    if (standAndScienceVo.get(i).getPubTime() != null) {
                        pubTime = sdf.format(standAndScienceVo.get(i).getPubTime());
                    }
                    RowRenderData row = RowRenderData.build(new TextRenderData(pubTime, textStyle),
                            new TextRenderData(standAndScienceVo.get(i).getTitle(), textStyle), new TextRenderData(standAndScienceVo.get(i).getDeptName(), textStyle),
                            new TextRenderData(standAndScienceVo.get(i).getMyDuty(), textStyle));
                    row.setRowStyle(rowStyle);
                    standRowList.add(row);
                }
            }
        }
        detailTable.setStandAndScienceVo(standRowList);

        //参加技能竞赛获奖情况
        List<ContestInfoVo> contestInfoVo = data.getContestInfoVo();
        List<RowRenderData> contestRowList = new ArrayList<>();
        RowRenderData row5 = RowRenderData.build("","","","","");//加一行空行
        contestRowList.add(row5);
        if(contestInfoVo != null && contestInfoVo.size() > 0){
//            for(ContestInfoVo vo:contestInfoVo){
            for(int i=contestInfoVo.size()-1;i>=0;i--){
                if(contestInfoVo.get(i).getIsHide() == null || !(contestInfoVo.get(i).getIsHide().equals("0"))) {
                    String awardDate = "";
                    if (contestInfoVo.get(i).getAwardDate() != null) {
                        awardDate = sdf.format(contestInfoVo.get(i).getAwardDate());
                    }
                    RowRenderData row = RowRenderData.build(new TextRenderData(awardDate, textStyle),
                            new TextRenderData(contestInfoVo.get(i).getCompName(), textStyle), new TextRenderData(contestInfoVo.get(i).getCompRank(), textStyle),
                            new TextRenderData(contestInfoVo.get(i).getAwardName(), textStyle), new TextRenderData(contestInfoVo.get(i).getHostOrg(), textStyle));
                    row.setRowStyle(rowStyle);
                    contestRowList.add(row);
                }
            }
        }
        detailTable.setContestInfoVo(contestRowList);

        //承担技艺传授、技能培训工作情况
        List<TeachArtVo> teachArtVo = data.getTeachArtVo();
        List<RowRenderData> teachRowList = new ArrayList<>();
        RowRenderData row6 = RowRenderData.build("","","");//加一行空行
        teachRowList.add(row6);
        if(teachArtVo != null && teachArtVo.size() > 0){
//            for(TeachArtVo vo:teachArtVo){
            for(int i=teachArtVo.size()-1;i>=0;i--){
                if(teachArtVo.get(i).getIsHide() == null || !(teachArtVo.get(i).getIsHide().equals("0"))) {
                    String start = "";
                    String end = "";
                    if (teachArtVo.get(i).getStartTime() != null) {
                        start = sdf.format(teachArtVo.get(i).getStartTime());
                    }
                    if (teachArtVo.get(i).getEndTime() != null) {
                        end = sdf.format(teachArtVo.get(i).getEndTime());
                    }
                    RowRenderData row = RowRenderData.build(new TextRenderData(start + "-" + end, textStyle),
                            new TextRenderData(teachArtVo.get(i).getContent(), textStyle), new TextRenderData(teachArtVo.get(i).getCertifier(), textStyle));
                    row.setRowStyle(rowStyle);
                    teachRowList.add(row);
                }
            }
        }
        detailTable.setTeachArtVo(teachRowList);

        //获得荣誉称号
        List<HonorDatasVo> honorDatasVo = data.getHonorDatasVo();
        List<RowRenderData> honorRowList = new ArrayList<>();
        RowRenderData row7 = RowRenderData.build("","","");//加一行空行
        honorRowList.add(row7);
        if(honorDatasVo != null && honorDatasVo.size() > 0){
//            for(HonorDatasVo vo:honorDatasVo){
            for(int i=honorDatasVo.size()-1;i>=0;i--){
                if(honorDatasVo.get(i).getIsHide() == null || !(honorDatasVo.get(i).getIsHide().equals("0"))) {
                    String acquTime = "";
                    if (honorDatasVo.get(i).getAcquTime() != null) {
                        acquTime = sdf.format(honorDatasVo.get(i).getAcquTime());
                    }
                    RowRenderData row = RowRenderData.build(new TextRenderData(acquTime, textStyle),
                            new TextRenderData(honorDatasVo.get(i).getHonorName(), textStyle), new TextRenderData(honorDatasVo.get(i).getAwardUnit(), textStyle));
                    row.setRowStyle(rowStyle);
                    honorRowList.add(row);
                }
            }
        }
        detailTable.setHonorDatasVo(honorRowList);
        datas.setDetailTable(detailTable);

        try {
            //获取头像
            TouXiangVo iamges = getTouXiang(erpNo);
            if(iamges != null && iamges.getInputStream()!=null){
                datas.setPic(new PictureRenderData(100, 160,".jpg",
                        iamges.getInputStream()));
            }
            ClassPathResource resource = new ClassPathResource("/templates/technical_report_form.docx");
            inputStream = resource.getInputStream();
            Configure config = Configure.newBuilder().bind("detail_table", new DetailTablePolicy()).build();
            template = XWPFTemplate.compile(inputStream,config).render(datas);
            String tempfilePath= UUID.randomUUID() +".docx";
            out = new FileOutputStream(tempfilePath);
            template.write(out);
            out.flush();
            responseWord(response,tempfilePath,filename);
            //删除临时文件
            file = new File(tempfilePath);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                if (out!=null){
                    out.close();
                }
                if (template!=null){
                    template.close();
                }
                if (file != null) {// 删除临时文件
                    if(file.exists()){
                        file.delete();
                    }
                }
            }catch (Exception e){
                log.error("关闭异常",e);
            }
        }
    }

    static SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyyMMddHHmmss");

    private void responseWord(HttpServletResponse response,String path,String filename){
        File file = null;
        InputStream in = null;
        ServletOutputStream out = null;
        try{
            String downloadFileName=filename+simpleDateFormat.format(new Date())+".docx";
            file = new File(path);
            in = new FileInputStream(file);
            response.setCharacterEncoding("utf-8");
            response.setHeader("Cache-Control", "");
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename="
                    .concat(String.valueOf(URLEncoder.encode(downloadFileName, "UTF-8"))));
            out = response.getOutputStream();
            byte[] buffer = new byte[512];
            int bytesToRead = -1;
            // 用响应对象response中的输出流读取生成好的文件
            while ((bytesToRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesToRead);
            }
            out.flush();
        }catch (Exception ex){
            log.error("product word fail..",ex);
        }finally {
            if (in != null) {
                try {
                    in.close();
                    if (out != null) {
                        out.close();
                    }
//                    if (file != null) {// 删除临时文件
//                        if(file.exists()){
//                            file.delete();
//                        }
//                    }
                } catch (IOException e) {
                    log.error("删除删除临时文件出错:" + e);
                }
            }
        }
    }

    /**
     * 获取头像
     * @param erpNo
     * @return
     */
    public TouXiangVo getTouXiang(String erpNo){
        TouXiangVo touXiangVo = null;
        InputStream inputStream = null;
        String fileId=null;
        String name=null;
        //通过ERP号查询头像Id
        ResultData resultData = fileServerCall.findFileList("personManage",erpNo,"userHead");
        JSONArray jsonArray =null;
        JSONObject obj =null;
        if(null != resultData) {
            log.info("获取头像数据为--"+resultData.toString());
            if(null != resultData.getData()) {
                jsonArray = JSONArray.fromObject(resultData.getData());
                if((null != jsonArray)&&(0 < jsonArray.size())) {
                    for(int i=0;i<jsonArray.size();i++) {
                        obj = (JSONObject) jsonArray.get(i);
                        if(null != obj) {
                            fileId = obj.getString("id");
                            name = obj.getString("oldFileName");
                        }
                    }
                }
            }
        }
        //下载文件
        if(fileId != null){
            try {
                Response response = fileServerCall.downloadFile(fileId);

                //判断是否下载成功
                if(response.status()==200) {
                    Response.Body body = response.body();
                    inputStream = body.asInputStream();
//                    inputStream = new FileInputStream(new File("test_one.png"));
                    touXiangVo = new TouXiangVo();
                    touXiangVo.setName(name);
                    touXiangVo.setInputStream(inputStream);
                }

            }catch (Exception e){
                log.error("下载文件失败！", e);
            }

        }

        return touXiangVo;
    }


}
